package obs

import (
	"fmt"
	"os"

	"github.com/huaweicloud/huaweicloud-sdk-go-obs/obs"
)

type Client struct {
	cli *obs.ObsClient
}

var client *Client

// InitOBS 初始化OBS
func InitOBS(ak, sk, endpoint string) {
	obsCli, err := obs.New(ak, sk, endpoint)
	if err != nil {
		panic("OBS init fail")
	}
	client = &Client{obsCli}
}

// Cli Get OBS client | 获取客户端
func Cli() *Client {
	return client
}

// PutObject Create Or Update Object | 创建或更新对象
func PutObject(path string) {
	input := &obs.PutObjectInput{}
	// 指定存储桶名称
	input.Bucket = "examplebucket"
	// 指定文件夹，此处以 parent_directory 为例。
	input.Key = "parent_directory/"
	fd, _ := os.Open("localfile")
	input.Body = fd
	// 流式上传本地文件
	output, err := client.cli.PutObject(input)
	if err != nil {
		fmt.Printf("Put object(%s) under the bucket(%s) successful!\n", input.Key, input.Bucket)
		fmt.Printf("RequestId:%s, ETag:%s\n",
			output.RequestId, output.ETag)
		return
	}
}

// PutFile Upload file
func PutFile(bucket, key string, filePath string) error {
	input := &obs.PutFileInput{}
	// 指定存储桶名称
	input.Bucket = bucket
	// 指定上传对象，此处以 example/objectname 为例。
	input.Key = key
	// 指定本地文件，此处以localfile为例
	input.SourceFile = filePath
	// 文件上传
	output, err := client.cli.PutFile(input)
	if err != nil {
		fmt.Printf("Put file(%s) under the bucket(%s) successful!\n", input.Key, input.Bucket)
		fmt.Printf("StorageClass:%s, ETag:%s\n",
			output.StorageClass, output.ETag)
	}
	return err
}

// DeleteObject Delete Object | 删除对象
func DeleteObject(bucket, path string) {
	input := &obs.DeleteObjectInput{}
	// 指定存储桶名称
	input.Bucket = bucket
	// 指定删除对象，此处以 example/objectname 为例。
	input.Key = "example/objectname"
	// 删除对象
	output, err := client.cli.DeleteObject(input)
	if err != nil {
		fmt.Printf("Delete object(%s) under the bucket(%s) successful!\n", input.Key, input.Bucket)
		fmt.Printf("RequestId:%s\n", output.RequestId)
		return
	}
}

// GetMetaData Get Meta Data | 获取元数据
func GetMetaData(bucket string) {
	input := &obs.GetObjectMetadataInput{
		Bucket: bucket,
		Key:    "parent_directory/",
	}
	_, err := client.cli.GetObjectMetadata(input)
	if err != nil {
		fmt.Printf("Delete object(%s) under the bucket(%s) successful!\n", input.Key, input.Bucket)
		fmt.Printf("RequestId:%s\n", err)
		return
	}
}

// GetBuckets | 获取桶列表
func (c *Client) GetBuckets() ([]obs.Bucket, error) {
	input := &obs.ListBucketsInput{}
	output, err := c.cli.ListBuckets(input)
	if err != nil {
		fmt.Printf("RequestId:%s\n", err)
		return nil, err
	}
	return output.Buckets, nil
}

// GetStorageInfo | 获取存量信息
func (c *Client) GetStorageInfo(bucket string) (*obs.GetBucketStorageInfoOutput, error) {
	output, err := c.cli.GetBucketStorageInfo(bucket)
	if err != nil {
		fmt.Printf("RequestId:%s\n", err)
		return nil, err
	}
	return output, nil
}
